//
//  LBProFilter.mm
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 11/28/12.
//  Copyright (c) 2012 UIT. All rights reserved.
//

#include <iostream>
#include "LBProFilter.h"
#include "LBTexture.h"

char proFragShader[]=""

"precision lowp float;  "

"varying highp vec2 vtexCoor;"
"varying highp vec2 vtexCoor2;"

"uniform sampler2D texture;"
"uniform sampler2D texture2; "
"varying vec4 vposition;"

"float safeColorF(float color){"
"    if(color > 1.0) color = 1.0;"
"    else if(color < 0.0) color = 0.0;"
"    return color;"
"}"

"vec4 safeColor(vec4 color){"
"    color.r = safeColorF(color.r);"
"    color.g = safeColorF(color.g);"
"    color.b = safeColorF(color.b);"
"    return color;"
"}"

//saturation function
"vec4 saturationColor(vec4 color, float saturation){"
"float avg = (color.r + color.g + color.b)/3.0; "
"color.r = avg + saturation*(color.r - avg); "
"color.g = avg + saturation*(color.g - avg);"
"color.b = avg + saturation*(color.b - avg);"
"color = safeColor(color);"
"return color;"
"}"
//END saturation function

//contrast function
"vec4 contrastColor(vec4 color, float contrast){"
"color.r = (color.r - 0.5)*contrast + 0.5;"
"color.g = (color.g - 0.5)*contrast + 0.5;"
"color.b = (color.b - 0.5)*contrast + 0.5;"
"color = safeColor(color);"
"return color;"
"}"
//END contrast function



// hard light blend function
"vec4 hardLight(vec4 base, vec4 blend, float opacity){"
"   vec4 result =  base;"
"    if (blend.r > 0.5) result.r = 1.0 - (1.0-base.r) *(1.0-2.0*(blend.r-0.5));"
"    else result.r = base.r * (2.0*blend.r);"

"    if (blend.g > 0.5) result.g = 1.0 - (1.0-base.g) *(1.0-2.0*(blend.g-0.5));"
"    else result.g = base.g * (2.0*blend.g);"

"    if (blend.b > 0.5) result.b = 1.0 - (1.0-base.b) *(1.0-2.0*(blend.b-0.5));"
"    else result.b = base.b * (2.0*blend.b);"

"    result = mix(base, result, opacity);"
"    return result;"
"}"
// END hard light blend function

"void main()"
"{"
    
"    vec4 baseColor = texture2D(texture, vtexCoor);"
"   lowp vec4 texture2Color = texture2D(texture2, vtexCoor2);"

"   vec4 result = baseColor;"
"    result = saturationColor(result, 1.15);"
"    result = hardLight(result, texture2Color, 0.7);"
"    baseColor = contrastColor(result, 1.2);"

"   gl_FragColor = result;"

"}";


LBProFilter::LBProFilter(){
    init(0, proFragShader);
}